package com.xiaoxi.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xiaoxi.yygh.hosp.repository.DepartmentRepository;
import com.xiaoxi.yygh.hosp.service.DepartmentService;
import com.xiaoxi.yygh.model.hosp.Department;
import com.xiaoxi.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    
    @Autowired
    private DepartmentRepository departmentRepository;

    // 上传科室信息
    @Override
    public void save(Map<String, Object> paramMap) {
        String paramMapString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(paramMapString, Department.class);
        
        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        
        if(departmentExist != null){
            // 修改
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            
            departmentRepository.save(departmentExist);
        }else {
            // 添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            
            departmentRepository.save(department);
        }

    }

    // 查询科室信息
    @Override
    public Page<Department> findPageDepartment(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        // 创建 Pageable 对象
        // 当前页从 1 开始的，-1
        Pageable pageable = PageRequest.of(page - 1, limit);
        
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        
        //创建 Example 对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                        .withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    // 删除科室信息
    @Override
    public void remove(String hoscode, String depcode) {
        // 根据 医院编号 和 科室编号 查询数据库是否有数据
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        
        if (department != null){
            // 删除
            departmentRepository.deleteById(department.getId());
        }

    }
}
